import config from '../../../config';
import { City } from '../../City';
import { ResidentialZone } from '../zones/ResidentialZone';
import { Development } from './Development';
import { SimModule } from './SimModule';
import { Citizen } from './../../Citizen';

/** 居民出入建筑的逻辑 */
export class Resident extends SimModule {

    private _zone: ResidentialZone;

    private _residents: Citizen[] = [];

    constructor(zone: ResidentialZone) {
        super();
        this._zone = zone;
    }

    /** 居民数量 */
    get count() {
        return this._residents.length;
    }

    /** 建筑可居住的最大人数 */
    get maximum() {
        return Math.pow(config.modules.residents.maxResidents, this._zone.development.level);
    }


    simulate(city: City) {
        // If building is abandoned, all residents are evicted and no more residents are allowed to move in.
        if (this._zone.development.state === Development.state.abandoned && this._residents.length > 0) {
            this.dispose();
        } else if (this._zone.development.state === Development.state.developed) {
            // Move in new residents if there is room
            if (this._residents.length < this.maximum && Math.random() < config.modules.residents.residentMoveInChance) {
                this._residents.push(new Citizen(this._zone));
            }
        }

        for (const resident of this._residents) {
            resident.simulate(city);
        }
    }

    dispose() {
        for (const resident of this._residents) {
            resident.dispose();
        }
        this._residents = [];
    }

    toHTML() {
        let html = `<div class="info-heading">Residents (${this._residents.length}/${this.maximum})</div>`;

        html += '<ul class="info-citizen-list">';
        for (const resident of this._residents) {
            html += resident.toHTML();
        }
        html += '</ul>';

        return html;
    }
}